import { defineStore } from 'pinia'
import { loginApi, getInfoApi, logoutApi } from '@/api/default/user'
import { useStorage } from '@vueuse/core'
import { type Ref, ref } from 'vue'
import type { LoginData, UserInfo } from '@/api/default/user/types'
import { clearToken, getToken, setToken, updateGlobalConfig } from '@/utils/auth'
import { store } from '@/stores/index'
import { resetRouter } from '@/router'

export const useUserStore = defineStore('user', () => {
  const user: Ref<UserInfo> = ref({})
  // const user = {}
  const token = ref(getToken())
  /**
   * 登录
   *
   * @returns
   * @param loginData
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          user.value = response.data
          token.value = response.data.token
          setToken(response.data.token)
          updateGlobalConfig()
          resolve(response.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo(): Promise<UserInfo> {
    return new Promise((resolve, reject) => {
      getInfoApi(token.value)
        .then(({ data }) => {
          if (!data) {
            reject('验证失败，请重新登录。')
            return
          }
          if (!data.roles || data.roles.length <= 0) {
            reject('getUserInfo：角色必须是非null数组！')
            return
          }
          user.value = data
          resolve(data)
        })
        .catch((error) => {
          console.log('error', error)
          reject(error)
        })
    })
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          token.value = ''
          clearToken()
          location.reload() // 清空路由
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      token.value = ''
      clearToken()
      resetRouter()
      resolve()
    })
  }

  return {
    token,
    user,
    login,
    getUserInfo,
    logout,
    resetToken
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
